package cn.caplike.demo.netty.in_outbound;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

@SuppressWarnings("SpellCheckingInspection")
public class MyServer {

    public static void main(String[] args) throws Exception {
        // @formatter:off
        final EventLoopGroup /* EventLoopGroup (extends EventExecutorGroup): 持有多个 EventLoop (extends EventExecutor) */
                 // 负责接收客户端的连接(不处理这个链接,作为Acceptor存在), 转发到 childGroup
                 parentGroup = new NioEventLoopGroup( /* See:io.netty.util.concurrent.MultithreadEventExecutorGroup.MultithreadEventExecutorGroup(int, java.util.concurrent.Executor, io.netty.util.concurrent.EventExecutorChooserFactory, java.lang.Object...)*/
                     1 /* 用 1 个线程侦听. Main Reactor.
                          不指定的话则会用核心数 * 2
                          See:io.netty.channel.MultithreadEventLoopGroup.MultithreadEventLoopGroup(int, java.util.concurrent.Executor, java.lang.Object...) */),
                  childGroup = new NioEventLoopGroup() // 真正完成请求处理的逻辑
        ;

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(parentGroup/* The EventLoopGroup which is used to handle all the events for the to-be-created Channel */, childGroup)
                           .channel(NioServerSocketChannel.class)
                         //.handler(ChannelHandler)
                           .childHandler(new MyServerChannelInitializer()/* childHandler */) // 服务于 childGroup
            ;

            ChannelFuture channelFuture = serverBootstrap// Create a new Channel and bind it.
                                                         .bind(8899) /* io.netty.bootstrap.AbstractBootstrap.doBind */
                                                         .sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            parentGroup.shutdownGracefully();
             childGroup.shutdownGracefully();
        }
    }
}
